package com.example.sharesinfo.fragment.trade;


import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.CommonAdapter;
import com.example.sharesinfo.adapter.CommonViewHolder;
import com.example.sharesinfo.base.BaseFragment;
import com.example.sharesinfo.bean.PositionBean;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.fragment.IndexFragment;
import com.example.sharesinfo.model.PositionModel;
import com.example.sharesinfo.ui.SharesInfoActivity;
import com.example.sharesinfo.utils.CommonUtils;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class TradingBuyFragment extends BaseFragment implements View.OnClickListener {
    private TradingBuyFragment fa;
    private static final String LOGTAG = "TradingBuyFragment:";
    private static final int QUERYDATASUCCESS = 1001;
    private static final int QUERYDATAEMPTY = 1002;
    private static final int QUERYSTOCKSUCCESS = 1003;
    private static final int QUERYSTOCKFAILED = 1004;
    private static final int BUYSTOCKSUCCESS = 1005;
    private static final int BUYSTOCKFAILED = 1006;
    private View item_empty_view;
    //持仓列表
    private RecyclerView mPositionView;
    private CommonAdapter<PositionModel> mPositionAdapter;
    private List<PositionModel> mList = new ArrayList<>();
    //搜索
    private TextView tv_search;
    private EditText et_search;

    //查询结果的布局
    private LinearLayout ll_hint;
    private LinearLayout ll_search_result_title;
    private LinearLayout ll_search_result_data;
    private TextView tv_stock_name;
    private TextView tv_stock_nowPrice;
    private TextView tv_zdf;
    private TextView tv_zdj;
    //购买股票
    private EditText et_num;
    private Button btn_buy;
    private int buyNumber;
    private TextView tv_add;
    private TextView tv_reduce;
    private String StockCode;
    private String userId;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case QUERYDATASUCCESS:
                    if (mList.size() > 0) {
                        mList.clear();
                    }
                    PositionBean result = (PositionBean) msg.obj;
                    LogUtils.i(LOGTAG + "size:" + result.getData().size());
                    if (result.getData().size() > 0) {
                        item_empty_view.setVisibility(View.GONE);
                        mList.addAll(result.getData());
                        mPositionAdapter.notifyDataSetChanged();
                    } else {
                        item_empty_view.setVisibility(View.VISIBLE);
                    }

                    break;
                case QUERYDATAEMPTY:

                    break;
                case QUERYSTOCKSUCCESS:
                    //查询股票成功
                    JSONObject result1 = (JSONObject) msg.obj;
                    try {
                        StockCode = result1.getString("code");
                        tv_stock_name.setText(result1.getString("name"));
                        tv_stock_nowPrice.setText(result1.getString("nowPrice"));
                        tv_zdf.setText(result1.getString("diff_rate"));
                        tv_zdj.setText(result1.getString("diff_money"));
                        CommonUtils.setTextColor(tv_stock_nowPrice, result1.getString("nowPrice"));
                        CommonUtils.setTextColor(tv_zdf, result1.getString("diff_rate"));
                        CommonUtils.setTextColor(tv_zdj, result1.getString("diff_money"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    ll_search_result_title.setVisibility(View.VISIBLE);
                    ll_search_result_data.setVisibility(View.VISIBLE);
                    ll_hint.setVisibility(View.GONE);
                    Toast.makeText(getContext(), "查询成功", Toast.LENGTH_SHORT).show();
                    break;
                case QUERYSTOCKFAILED:
                    //查询股票失败
                    ll_search_result_title.setVisibility(View.GONE);
                    ll_search_result_data.setVisibility(View.GONE);
                    ll_hint.setVisibility(View.VISIBLE);
                    Toast.makeText(getContext(), "请输入正确的股票代码/名称", Toast.LENGTH_SHORT).show();
                    break;
                case BUYSTOCKSUCCESS:
                    queryData();
                    break;
                case BUYSTOCKFAILED:
                    Toast.makeText(getContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 404:
                    break;
            }
            return false;
        }
    });

    public TradingBuyFragment getFragment() {
        if (fa == null) {
            fa = new TradingBuyFragment();
        }
        return fa;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_trading_buy, null);
        initView(view);
        queryData();
        return view;
    }

    private void initView(View view) {
        buyNumber = 0;
        StockCode = "";
        userId = SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        tv_search = view.findViewById(R.id.tv_search);
        tv_search.setOnClickListener(this);
        et_search = view.findViewById(R.id.et_search);
        item_empty_view = view.findViewById(R.id.item_empty_view);
        ll_hint = view.findViewById(R.id.ll_hint);
        ll_search_result_title = view.findViewById(R.id.ll_search_result_title);
        ll_search_result_data = view.findViewById(R.id.ll_search_result_data);
        tv_stock_name = view.findViewById(R.id.tv_stock_name);
        tv_stock_nowPrice = view.findViewById(R.id.tv_stock_nowPrice);
        tv_zdf = view.findViewById(R.id.tv_zdf);
        tv_zdj = view.findViewById(R.id.tv_zdj);

        et_num = view.findViewById(R.id.et_num);
        tv_add = view.findViewById(R.id.tv_add);
        tv_reduce = view.findViewById(R.id.tv_reduce);
        tv_add.setOnClickListener(this);
        tv_reduce.setOnClickListener(this);

        btn_buy = view.findViewById(R.id.btn_buy);
        btn_buy.setOnClickListener(this);
        item_empty_view = view.findViewById(R.id.item_empty_view);
        mPositionView = view.findViewById(R.id.mPositionView);
        mPositionView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mPositionView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL));
        mPositionAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnBindDataListener<PositionModel>() {
            @Override
            public void onBindViewHolder(final PositionModel model, CommonViewHolder viewHolder, int type, int position) {
                viewHolder.setText(R.id.stock_name, model.getStockName());
                viewHolder.setText(R.id.stock_code, model.getStockCode());
                viewHolder.setText(R.id.stock_earnings, model.getProfit_or_Loss_Value());
                viewHolder.setText(R.id.stock_position, String.valueOf(model.getStockNumber()));
                viewHolder.setText(R.id.stock_latest_price, String.valueOf(model.getNowPrice()));
                CommonUtils.setTextColor((TextView) viewHolder.getView(R.id.stock_earnings), model.getProfit_or_Loss_Value());
                CommonUtils.setTextColor((TextView) viewHolder.getView(R.id.stock_position), String.valueOf(model.getStockNumber()));
                CommonUtils.setTextColor((TextView) viewHolder.getView(R.id.stock_latest_price), String.valueOf(model.getNowPrice()));
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SharesInfoActivity.startActivity(getContext(), model.getStockCode());
                    }
                });
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.trading_buy_sell_position_list_item;
            }
        });
        mPositionView.setAdapter(mPositionAdapter);
    }

    /**
     * 查询数据
     */
    private void queryData() {
        String url = "http://119.23.221.142/api/account/GetPositionList?UserId=" + userId;
        //+ SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                JSONObject object = new JSONObject(s);
                LogUtils.i(LOGTAG + s);
                if (object.getString("code").equals("200")) {
                    PositionBean bean = new Gson().fromJson(s, PositionBean.class);
                    message.what = QUERYDATASUCCESS;
                    message.obj = bean;
                    mHandler.sendMessage(message);
                } else {
                    message.what = QUERYDATAEMPTY;
                    message.obj = object.getString("data");
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    /**
     * 根据股票名称或者代码查询股票
     */
    private void queryStock(String NameOrCode) {
        String url = "http://119.23.221.142/api/account/GetBuyStockInfo?NameorCode=" + NameOrCode;
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                Message message = mHandler.obtainMessage();
                JSONObject object = new JSONObject(s);
                if (object.getString("code").equals("400")) {
                    //查询失败
                    message.what = QUERYSTOCKFAILED;
                    message.obj = "请输入正确的股票代码/名称";
                    mHandler.sendMessage(message);
                } else {
                    //查询成功
                    message.what = QUERYSTOCKSUCCESS;
                    message.obj = object;
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void OnFailed(String s) {

            }
        });

    }

    /**
     * 购买股票
     * 参数为UserId（用户Id）,
     * NameorCode（精确的股票名称和股票代码），
     * Number（购股数量））
     * POST
     */
    public void BuyStocks(String userid, String NameorCode, String Number) {
        String urlRoot = "http://119.23.221.142/api/account/BuyStocks?";
        Map<String, String> datas = new HashMap<String, String>();
        datas.put("UserId", userid);
        datas.put("NameorCode", NameorCode);
        datas.put("Number", Number);
        OkHttpUtils.getInstance().Post(urlRoot, null, datas,
                null, null, new OkHttpUtils.okHttpListener() {
                    Message message = mHandler.obtainMessage();

                    @Override
                    public void OnSuccess(String s, int code) throws JSONException {
                        JSONObject object = new JSONObject(s);
                        LogUtils.i(LOGTAG + s);
                        if (object.getString("code").equals("200")) {
                            message.what = BUYSTOCKSUCCESS;
                            mHandler.sendMessage(message);
                        } else {
                            message.what = BUYSTOCKFAILED;
                            message.obj = object.getString("message");
                            mHandler.sendMessage(message);
                        }


                    }

                    @Override
                    public void OnFailed(String s) {
                        message.what = BUYSTOCKFAILED;
                        mHandler.sendMessage(message);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_add:
                if (TextUtils.isEmpty(et_num.getText().toString())) {
                    buyNumber = buyNumber + 1;
                    et_num.setText(String.valueOf(buyNumber));
                } else {
                    buyNumber = Integer.parseInt(et_num.getText().toString()) + 1;
                    et_num.setText(String.valueOf(buyNumber));
                }
                break;
            case R.id.tv_reduce:
                if (buyNumber != 0) {
                    if (!TextUtils.isEmpty(et_num.getText().toString())) {
                        buyNumber = Integer.parseInt(et_num.getText().toString()) - 1;
                        et_num.setText(String.valueOf(buyNumber));
                    }
                } else {
                    et_num.setText(String.valueOf(buyNumber));
                }
                break;
            case R.id.tv_search:
                if (TextUtils.isEmpty(et_search.getText().toString())) {
                    Toast.makeText(getActivity(), "输入不能空", Toast.LENGTH_SHORT).show();
                } else {
                    queryStock(et_search.getText().toString());
                }
                break;
            case R.id.btn_buy:
                if (TextUtils.isEmpty(et_search.getText().toString())) {
                    Toast.makeText(getActivity(), "请先输入股票代码/名称", Toast.LENGTH_SHORT).show();
                } else {
                    if (TextUtils.isEmpty(et_num.getText().toString())) {
                        Toast.makeText(getActivity(), "请输入购买数量", Toast.LENGTH_SHORT).show();
                    } else {
                        if (CommonUtils.isNumeric(et_num.getText().toString())) {
                            buyNumber = Integer.parseInt(et_num.getText().toString());
                            if (!StockCode.equals("")) {
                                BuyStocks(userId, StockCode, String.valueOf(buyNumber));
                            } else {
                                Toast.makeText(getActivity(), "请查询正确的股票", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(getActivity(), "请输入整数数量", Toast.LENGTH_SHORT).show();
                        }
                    }
                }

                break;
        }
    }
}
